﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;
using System.Data.SqlClient;
using FastReport.Export.Pdf;

namespace FaturaPdf
{
    public partial class frmMain : XtraForm
    {
        public frmMain()
        {
            InitializeComponent();
        }

        List<Evrak> _evraklar = new List<Evrak>();

        private void EvrakKontrol()
        {
            if (string.IsNullOrEmpty(Config.GetConfig.GetValue(Parametre.Server)))
            {
                return;
            }
            using (SqlConnection _cn = new SqlConnection(Config.GetConfig.GetValue(Parametre.ConStr)))
            {
                _cn.Open();
                using (SqlCommand cmd = new SqlCommand("SELECT evr.egk_RECno,evr.egk_evr_seri,evr.egk_evr_sira,CARI_HESAPLAR.cari_EMail FROM EVRAK_ACIKLAMALARI as evr INNER JOIN CARI_HESAP_HAREKETLERI as cr ON evr.egk_evr_seri = cr.cha_evrakno_seri AND evr.egk_evr_sira = cr.cha_evrakno_sira INNER JOIN CARI_HESAPLAR ON cr.cha_kod = CARI_HESAPLAR.cari_kod WHERE     (evr.egk_hareket_tip = 0) AND (evr.egk_evr_tip = 63) AND (evr.egk_evracik10 <> N'MAIL') AND (CARI_HESAPLAR.cari_EMail <> '') AND (CARI_HESAPLAR.cari_POS_ongtaksayi=1)", _cn))
                {
                    SqlDataReader rd = cmd.ExecuteReader();
                    while (rd.Read())
                    {
                        if (Config.GetConfig.GetValue(Parametre.evrakSerileri, "").IndexOf(rd.GetString(1)) == -1)
                        {
                            _evraklar.Add(new Evrak()
                            {
                                Id = rd.GetInt32(0),
                                Seri = rd.GetString(1),
                                Sira = rd.GetInt32(2),
                                email = rd.GetString(3)
                            });
                        }
                    }
                    rd.Close();
                }
                _cn.Close();
            }
        }

        private void EvrakSonlandir(int id)
        {
            using (SqlConnection _cn = new SqlConnection(Config.GetConfig.GetValue(Parametre.ConStr)))
            {
                _cn.Open();
                using (SqlCommand cmd = new SqlCommand("UPDATE EVRAK_ACIKLAMALARI SET egk_evracik10='MAIL' WHERE     (egk_RECno = @id)", _cn))
                {
                    cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
                    cmd.ExecuteNonQuery();
                }
                _cn.Close();
            }
        }


        private void frmMain_Load(object sender, EventArgs e)
        {
            for (int i = 1; i < vGridControl1.Rows.Count; i++)
            {
                if (!string.IsNullOrEmpty(vGridControl1.Rows[i].Properties.FieldName)) vGridControl1.Rows[i].Properties.Value = Config.GetConfig.GetValue((Parametre)Enum.Parse(typeof(Parametre), vGridControl1.Rows[i].Properties.FieldName));
            }
        }

        private void btnKaydet_Click(object sender, EventArgs e)
        {
            for (int i = 1; i < vGridControl1.Rows.Count; i++)
            {
                if (vGridControl1.Rows[i].Properties.Value != null)
                    Config.GetConfig.Add((Parametre)Enum.Parse(typeof(Parametre), vGridControl1.Rows[i].Properties.FieldName), vGridControl1.Rows[i].Properties.Value.ToString());
            }
            Config.GetConfig.Save();
            this.Close();
        }

        private void çıkışToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private bool isShowDialog = false;
        private void ayarlarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            isShowDialog = true;
            this.Show();
            this.BringToFront();
        }

        private void frmMain_Activated(object sender, EventArgs e)
        {
            if (!isShowDialog)
            {
                isShowDialog = false;
                this.Hide();
            }
        }

        private void frmMain_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                isShowDialog = false;
                this.Hide();
            }
        }

        private void dizaynToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (File.Exists(Application.StartupPath + "\\dizayn.frx"))
            {
                report1.Load(Application.StartupPath + "\\dizayn.frx");
            }
            else
            {
                report1.FileName = Application.StartupPath + "\\dizayn.frx";
            }
            report1.Design();
        }


        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            timer1.Stop();
            timer1.Enabled = false;
            EvrakKontrol();
        }

        private void SendToPdf(Evrak evr)
        {
            if (File.Exists(Application.StartupPath + "\\dizayn.frx"))
            {
                report1.Load(Application.StartupPath + "\\dizayn.frx");
                FastReport.Data.TableDataSource data = report1.GetDataSource("Table") as FastReport.Data.TableDataSource;
                data.Connection.ConnectionString = Config.GetConfig.GetValue(Parametre.ConStr);
                data.SelectCommand = data.SelectCommand.Replace("@seri", "'" + evr.Seri + "'").Replace("@sira", evr.Sira.ToString());
                data.Connection.CommandTimeout = int.MaxValue;
                report1.Prepare();

                string filename = Path.Combine(Application.StartupPath, new Random().Next(1000, 999999999).ToString() + ".pdf");

                PDFExport pdf = new PDFExport();
                pdf.Export(report1, filename);

                string emailuser = Config.GetConfig.GetValue(Parametre.mailUser);
                string emailpwd = Config.GetConfig.GetValue(Parametre.emailPwd);
                string kimden = Config.GetConfig.GetValue(Parametre.email);
                string sunucu = Config.GetConfig.GetValue(Parametre.smtpServer);

                if (Config.GetConfig.GetValue(Parametre.ServerType) == "Gmail")
                {
                    if (eMail.Get.Gmail2(kimden, evr.email, emailuser, emailpwd, "Fatura", "Fatura ektedir.Ekteki dosyayı açabilmeniz için Adobe Acrobat Reader programının bilgisayarınızda kurulu olması gerekmektedir.", sunucu, filename))
                    {
                        EvrakSonlandir(evr.Id);
                    }
                }
                else
                {
                    if (eMail.Get.Smtp(kimden, evr.email, emailuser, emailpwd, "Fatura", "Fatura ektedir.Ekteki dosyayı açabilmeniz için Adobe Acrobat Reader programının bilgisayarınızda kurulu olması gerekmektedir.", sunucu, filename))
                    {
                        EvrakSonlandir(evr.Id);
                    }
                }

                File.Delete(filename);
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            foreach (Evrak evr in _evraklar)
            {
                SendToPdf(evr);
            }
            _evraklar.Clear();
            timer1.Enabled = true;
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.WorkerSupportsCancellation = true;
                backgroundWorker1.RunWorkerAsync();
            }
        }
    }
}
